<?php
require "./vendor/autoload.php";

use \Elasticsearch\ClientBuilder;
use Elasticsearch\Common\Exceptions\Missing404Exception;

$host = ["127.0.0.1:10001"];
$client = ClientBuilder::create()->setHosts($host)->build();


$index = [
    "index" => "user",
    'body' => [
        'settings' => [
            'number_of_shards' => 1,
            'number_of_replicas' => 3
        ],
    ],
];

//$doc = [
//        "id" => 22,
//        "index" => "user",
//        "body" => [
//            "sex" => "女",
//        ],
//];

//$params = [
//    "index" => "user",
//    "id" => 1,
//];
//
//$docs = [];
//for ($i = 1; $i <= 10; $i++) {
//    $docs['body'][] = [
//        "index" => [
//            "_index" => "user",
//            "_id" => $i,
//        ]
//
//    ];
//
//    $docs['body'][] = [
//        "name" => "wyq$i",
//        "sex" => $i%2 ==0 ? "男" : "女",
//    ];
//}
    $res = $client->indices()->create($index);//创建索引
    var_dump($res);



//$res = $client->indices()->get($index); //查询索引

//$res = $client->indices()->delete($index);//删除索引

//$res = $client->create($doc);//创建doc
//$res = $client->bulk($docs); //批量创建doc
//var_dump($res);
//$update = [
//    "id" => 23,
//    "index" => "user",
//    "body" => [
//        "doc" => [
//            "sex" => "男"
//        ],
//    ],
//];

//$res = $client->update($update); //修改doc
//$res = $client->delete($params);//删除doc
//var_dump($res);
//$res = $client->search($index);
//var_dump($res);

//$res = $client->getSource($params);


function CreateDocs($indexName = "",$client, $data)
{
    $params = ["body" => []];
    foreach ($data as $k => $v) {
        $params['body'][] = [
            'index' => [
                '_index' => $indexName,
                "_id" => $v['id'],
            ]
        ];
        $params['body'][] = $v;
    }
    try {
        $response = $client->bulk($params);
        $res = [
            'code' => 200,
            'message' => "success",
            'data' => $response
        ];
    } catch (Missing404Exception $exception) {
        $res = [
            'code' => $exception->getCode(),
            'message' => json_decode($exception->getMessage(), true),
            'data' => [],
        ];
    }
    return $res;
}

$data = [
    ['id'=>1,'name' => "fj1" , "sex"=>"男"],
    ['id'=>2,'name' => "fj2" , "sex"=>"男"],
    ['id'=>3,'name' => "fj3" , "sex"=>"男"],
    ['id'=>4,'name' => "fj4" , "sex"=>"男"],
    ['id'=>5,'name' => "fj5" , "sex"=>"男"],
];


//$res = CreateDocs('user',$client,$data);